module SmtpcomApi
  class Sender < Client
    READERS    = [:id, :sent, :allowed_ips]
    ACCESSORS  = [:label, :is_ip_based, :login, :max_quota, :password]
    ATTRIBUTES = READERS + ACCESSORS

    include Helpers

    attr_accessor *ACCESSORS
    attr_reader   *READERS

    def initialize(label_or_id, api_key, api_host, attributes={})
      super(api_key, api_host)
      @label_or_id = label_or_id
      attributes = get(:sender, {:pl => @label_or_id})['sender'] if attributes.empty?
      set_attributes(attributes)
      @allowed_ips ||= []
      
      [:summary, :delivery, :campaigns, :complaints, :queue].each do |key|
        define_singleton_method key do |options={}|
          get(key, options.merge({:pl => @label_or_id}))[key.to_s]
        end
      end 
    end

    def reload
      set_attributes get(:sender, {:pl => @label_or_id})['sender']
      self
    end

    def campaign(campaign_id)
      get(:campaign, {:pl => [@label_or_id, campaign_id]})['campaign']
    end

    def save
      update = attributes.select{|k| ACCESSORS.include? k}
      update.delete(:password) if update[:password].nil?
      result = put :sender, :sender => update, :pl => @label_or_id
      @label_or_id = @label
      self.password = nil
      self
    end

    def add_allowed_ip(ip)
      @allowed_ips << post(:sender_allowed_ips, {:allowed_ip => {:range => ip}, :pl => @label_or_id})['allowed_ip']
    end

    def remove_allowed_ip(ip)
      if @allowed_ips.map{|aip| aip['range']}.include?(ip)
        delete(:update_sender_allowed_ip, {:pl => [@label_or_id, ip]})
        @allowed_ips.reject!{|aip| aip['range']==ip}
      end
    end

  end
end